#include "loginwindow.h"
#include "ui_loginwindow.h"
#include "mainwindow.h"
#include <QMessageBox>
#include <QKeyEvent>

LoginWindow::LoginWindow(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::LoginWindow)
    , mainWindow(nullptr)
{
    ui->setupUi(this);
    
    // 设置窗口属性
    setWindowFlags(Qt::Window | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint);
    setFixedSize(400, 300);
    
    // 连接信号和槽
    connect(ui->loginButton, &QPushButton::clicked, this, &LoginWindow::onLoginButtonClicked);
    
    // 设置默认焦点
    ui->usernameLineEdit->setFocus();
    
    // 允许回车键登录
    ui->usernameLineEdit->installEventFilter(this);
    ui->passwordLineEdit->installEventFilter(this);
}

LoginWindow::~LoginWindow()
{
    delete ui;
    if (mainWindow) {
        delete mainWindow;
    }
}

bool LoginWindow::validateLogin(const QString &username, const QString &password)
{
    return (username == DEFAULT_USERNAME && password == DEFAULT_PASSWORD);
}

void LoginWindow::onLoginButtonClicked()
{
    QString username = ui->usernameLineEdit->text().trimmed();
    QString password = ui->passwordLineEdit->text();
    
    if (username.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "请输入用户名！");
        ui->usernameLineEdit->setFocus();
        return;
    }
    
    if (password.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "请输入密码！");
        ui->passwordLineEdit->setFocus();
        return;
    }
    
    if (validateLogin(username, password)) {
        // 登录成功，创建并显示主窗口
        if (!mainWindow) {
            mainWindow = new MainWindow();
        }
        mainWindow->show();
        this->hide();
        
        // 清空输入框
        ui->usernameLineEdit->clear();
        ui->passwordLineEdit->clear();
    } else {
        QMessageBox::critical(this, "登录失败", "用户名或密码错误！\n\n默认用户名: ARM\n默认密码: PYT");
        ui->passwordLineEdit->clear();
        ui->usernameLineEdit->setFocus();
    }
}

bool LoginWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) {
            onLoginButtonClicked();
            return true;
        }
    }
    return QWidget::eventFilter(obj, event);
}